package com.maomao.book.service.impl;

import com.maomao.book.domain.BookOrder;
import com.maomao.book.domain.Member;
import com.maomao.book.repository.BookOrderRepository;
import com.maomao.book.repository.MemberRepository;
import com.maomao.book.service.BookOrderService;
import com.maomao.book.service.MemberService;
import com.maomao.book.strategy.PointStrategy;
import com.maomao.book.strategy.PointStrategyBuilder;
import com.maomao.book.strategy.PointStrategyContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

/**
 * implement the book order service
 *
 * @author kevin.mao
 */
@Service
@Slf4j
public class BookOrderServiceImpl implements BookOrderService {

    @Autowired
    private MemberRepository memberRepository;

    @Autowired
    private BookOrderRepository bookOrderRepository;

    private PointStrategyBuilder pointStrategyBuilder = new PointStrategyBuilder();


    @Transactional
    @Override
    public BookOrder saveBookOrder(BookOrder bookOrder) {

        // first select member
        Optional<Member> memberOpt = memberRepository.findById(bookOrder.getMemberId());
        if (!memberOpt.isPresent()) {
            throw new RuntimeException("Do not find the member with id:" + bookOrder.getMemberId());
        }

        Member member = memberOpt.get();
        PointStrategy pointStrategy = pointStrategyBuilder.build(member);
        PointStrategyContext context = new PointStrategyContext(pointStrategy);
        int point = context.calcPoint(bookOrder.getTotalPrice());
        member.setPoint(member.getPoint() + point);
        log.info("The member's name is {}.", member.getName());
        memberRepository.save(member);
        bookOrderRepository.save(bookOrder);
        return bookOrder;
    }

    @Override
    public Page<BookOrder> getBookOrderPage(int page, int size) {
        PageRequest pageable = PageRequest.of(page, size, Sort.Direction.DESC, "id");
        return bookOrderRepository.findAll(pageable);
    }

}
